﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcApplication2.Models;
using System.Data;
using MvcApplication2.Models.Form;
namespace MvcApplication2.Delegale.Concrete
{
    public class CategoryDelegate:Interface.ICategoryDelegate
    {
        
        private ProductDbcontext context;

        public CategoryDelegate(ProductDbcontext context)
        {
            this.context = context;
        }
        public IQueryable<Category> GetCategorys()
        {
            return context.Categorys;
        }
        public IList<Category> ListCategory()
        {
            return this.GetCategorys().ToList();
        }
        public Category GetCategoryByID(int id)
        {
            return context.Categorys.SingleOrDefault(p => p.Id == id);
        }

        public Category ConvetToEntityCategory(CategoryForm form)
        {
            Category obj = new Category();
            obj.Name = form.Name;
            obj.ParentId = form.ParentId;
            return obj;
        }

        public Category InsertCategory(Category Category)
        {
            try
            {
                context.Categorys.Add(Category);
                context.SaveChanges();
                return Category;
            }
            catch (Exception) { return null; }
        }

        public bool DeleteCategory(int CategoryID)
        {
            try
            {
                Category Category = context.Categorys.Find(CategoryID);
                context.Categorys.Remove(Category);
                context.SaveChanges();
                return true;
            }
            catch (Exception) { return false; }
        }

        public Category UpdateCategory(Category Category)
        {
            try
            {
                context.Entry(Category).State = EntityState.Modified;
                context.SaveChanges();
                return Category;
            }
            catch (Exception) { return null; }
        }
        public bool CheckNameCategory(string name)
        {
            return context.Categorys.Where(p => p.Name.Equals(name)).Any();
        }
    }
}